﻿using System.Windows;
using System.Windows.Media;
using Dimebrain.TweetSharp.Fluent;
using Dimebrain.TweetSharp.Extensions;
using WPFOAuthStarter.Properties;

namespace WPFOAuthStarter
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded( object sender, RoutedEventArgs e )
        {
            //TODO: Make sure you get a consumer key and secret from twitter
            //and put it in the settings file. Then you can remove this check.
            ////////////////////////////////////////////////////////////
            if ( string.IsNullOrEmpty( Settings.Default.ConsumerKey )
                || string.IsNullOrEmpty( Settings.Default.ConsumerSecret ) )
            {
                MessageBox.Show(
                    "You need to obtain a consumer key and consumer secret from Twitter and add them to the Settings.Settings file.",
                    "Can't continue", MessageBoxButton.OK, MessageBoxImage.Error );
                Close();
            }
            ///////////////////////////////////////////////////////////

            if ( !CheckHasAuthorization() )
            {
                PerformOAuthAuthorization();
            }
            else
            {
                AuthStatusLabel.Content = "Authorized";
                AuthStatusLabel.Foreground = Brushes.Green;
            }
        }

        private void PerformOAuthAuthorization()
        {
            var dlg = new OAuthDialog();
            bool? result = dlg.ShowDialog();
            if ( result.HasValue == result.Value )
            {
                if ( VerifyOAuthCredentials() )
                {
                    AuthStatusLabel.Content = "Authorized";
                    AuthStatusLabel.Foreground = Brushes.Green;
                }
            }
            else
            {
                AuthStatusLabel.Content = "Authorization cancelled.";
                AuthStatusLabel.Foreground = Brushes.Red;
                tryAgainButton.Visibility = Visibility.Visible;
            }
        }

        private bool CheckHasAuthorization()
        {
            bool authorized = false;
            if ( !string.IsNullOrEmpty( Settings.Default.AccessToken )
                 && !string.IsNullOrEmpty( Settings.Default.AccessTokenSecret ) )
            {
                authorized = VerifyOAuthCredentials();
            }
            else
            {
                AuthStatusLabel.Content = "Auth tokens not found.";
                AuthStatusLabel.Foreground = Brushes.Red;
            }
            return authorized;
        }

        private static bool VerifyOAuthCredentials()
        {
            bool authorized = false;
            var twitter = FluentTwitter.CreateRequest()
                .AuthenticateWith( Settings.Default.ConsumerKey, Settings.Default.ConsumerSecret,
                                  Settings.Default.AccessToken, Settings.Default.AccessTokenSecret )
                .Account().VerifyCredentials();
            var response = twitter.Request();
            var profile = response.AsUser();
            if ( profile != null )
            {
                authorized = true;
            }
            return authorized;
        }

        private void tryAgainBtn_Click( object sender, RoutedEventArgs e )
        {
            PerformOAuthAuthorization(); 
        }
    }
}
 